package com.zhentao.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhentao.mapper.SourceMapper;
import com.zhentao.pojo.DoctorSchedule;
import com.zhentao.pojo.ScheduleUpdateDTO;
import com.zhentao.pojo.Source;
import com.zhentao.service.DoctorScheduleService;
import com.zhentao.mapper.DoctorScheduleMapper;
import com.zhentao.service.SourceService;
import com.zhentao.vo.QueryParam;
import com.zhentao.vo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
* @author ls
* @description 针对表【doctor_schedule】的数据库操作Service实现
* @createDate 2025-05-08 18:45:40
*/
@Service
@Transactional
public class DoctorScheduleServiceImpl extends ServiceImpl<DoctorScheduleMapper, DoctorSchedule> implements DoctorScheduleService{
    @Autowired
    private DoctorScheduleMapper doctorScheduleMapper;
    @Autowired
    private SourceMapper sourceMapper;
    @Autowired
    private SourceService sourceService;

    @Override
    public List<DoctorSchedule> selectByDoctorId(Integer doctorId) {
        return doctorScheduleMapper.selectByDoctorId(doctorId);
    }

    @Override
    public Page<DoctorSchedule> findPage(QueryParam queryParam) {
        Page<DoctorSchedule> page = new Page<>(queryParam.getCurrent(),queryParam.getSize());
        QueryWrapper<DoctorSchedule> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("doctor_id",queryParam.getDoctorId());
        // 1. 先查询分页数据
        Page<DoctorSchedule> doctorSchedulePage = doctorScheduleMapper.selectPage(page, queryWrapper);

        // 2. 遍历每个排班记录补充sources
        doctorSchedulePage.getRecords().forEach(record -> {
            List<Source> sources = sourceMapper.selectByScheduleId(record.getScheduleId());
            record.setSources(sources);
        });

        return doctorSchedulePage; // 返回完整的分页结果

    }

    @Override
    public Result updateScheduleWithSources(ScheduleUpdateDTO dto) {
        try {
            // 1. 校验排班是否存在
            DoctorSchedule schedule = getById(dto.getScheduleId());
            if (schedule == null) {
                return Result.ERROR("排班记录不存在");
            }

            // 2. 更新排班基本信息
            updateScheduleDate(schedule, dto.getDate());

            // 3. 处理号源信息
            handleSources(dto);

            return Result.OK("更新成功");
        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return Result.ERROR("更新失败: " + e.getMessage());
        }
    }

    private void updateScheduleDate(DoctorSchedule schedule, String dateStr)
            throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date newDate = sdf.parse(dateStr);
        schedule.setDate(newDate);
        updateById(schedule);
    }

    private void handleSources(ScheduleUpdateDTO dto) {
        // 获取现有号源
        List<Source> existingSources = sourceService.lambdaQuery()
                .eq(Source::getScheduleId, dto.getScheduleId())
                .list();

        // 构建操作集合
        Map<Integer, Source> existingMap = existingSources.stream()
                .collect(Collectors.toMap(Source::getId, Function.identity()));

        List<Source> toUpdate = new ArrayList<>();
        List<Source> toAdd = new ArrayList<>();
        Set<Integer> receivedIds = new HashSet<>();

        // 处理每个传入的号源
        for (ScheduleUpdateDTO.SourceDTO sourceDTO : dto.getSources()) {
            if (sourceDTO.getId() != null) {
                // 更新操作
                if (existingMap.containsKey(sourceDTO.getId())) {
                    Source source = existingMap.get(sourceDTO.getId());
                    updateSourceFromDTO(source, sourceDTO);
                    toUpdate.add(source);
                    receivedIds.add(source.getId());
                }
            } else {
                // 新增操作
                Source newSource = new Source();
                newSource.setScheduleId(dto.getScheduleId());
                updateSourceFromDTO(newSource, sourceDTO);
                toAdd.add(newSource);
            }
        }

        // 处理删除操作
        List<Integer> toDelete = existingSources.stream()
                .filter(s -> !receivedIds.contains(s.getId()))
                .map(Source::getId)
                .collect(Collectors.toList());

        // 执行批量操作
        if (!toUpdate.isEmpty()) sourceService.updateBatchById(toUpdate);
        if (!toAdd.isEmpty()) sourceService.saveBatch(toAdd);
        if (!toDelete.isEmpty()) sourceService.removeByIds(toDelete);
    }

    private void updateSourceFromDTO(Source source, ScheduleUpdateDTO.SourceDTO dto) {
        source.setTimeSlot(dto.getTimeSlot());
        source.setTotal(dto.getTotal());
        source.setRemaining(dto.getRemaining());
        source.setFee(dto.getFee());
    }


}




